/**   
* @Title: CosUpload.java 
* @Package com.csis.framework.web.upload 
* @Description: TODO
* @author dailey  
* @date 15 Oct 2012
* @version V1.0   
*/
package com.csis.framework.web.upload;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csis.system.common.IStaticData;
import com.oreilly.servlet.multipart.FilePart;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.Part;

/**
 * @author dailey
 *
 */
public class CosUploadHandler {
	private Integer maxSize = 10 * 1024 * 1024;
	private String savePath;
	private boolean isAbsolute;
	private String saveDir;

	/**
	 * @return the maxSize
	 */
	public Integer getMaxSize() {
		return maxSize;
	}

	/**
	 * @param maxSize the maxSize to set
	 */
	public void setMaxSize(Integer maxSize) {
		this.maxSize = maxSize;
	}

	/**
	 * @return the savePath
	 */
	public String getSavePath() {
		return savePath;
	}

	/**
	 * @param savePath the savePath to set
	 */
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	/**
	 * @return the isAbsolute
	 */
	public Boolean getIsAbsolute() {
		return isAbsolute;
	}

	/**
	 * @param isAbsolute the isAbsolute to set
	 */
	public void setIsAbsolute(Boolean isAbsolute) {
		this.isAbsolute = isAbsolute;
	}

	public String getSaveDir(HttpServletRequest request) {
		if (!getIsAbsolute()) {
			return request.getSession().getServletContext().getRealPath(savePath);
		}
		return getSavePath();
	}

	public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		saveDir = savePath;
		if (!getIsAbsolute()) {
			saveDir = request.getSession().getServletContext().getRealPath(savePath);
		}
		MultipartParser multipartParser = new MultipartParser(request, getMaxSize());
		Part part = null;
		while ((part = multipartParser.readNextPart()) != null) {
			if (part.isParam()) {
				handleParam(part);
			} else if (part.isFile()) {
				FilePart filePart = (FilePart) part;
				handleFile(filePart, request, response);
			}
		}
	}

	/**
	 * @param part
	 */
	private void handleParam(Part part) {

	}

	/**
	 * @param filePart
	 * @throws IOException 
	 */
	private void handleFile(FilePart filePart, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		File dir = new File(saveDir);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		filePart.writeTo(dir);
		File file = new File(saveDir,filePart.getFileName());
		request.getSession().setAttribute(IStaticData.UPLOAD_IAMGE_FILE, file);
	}

}
